package testndk.testservice.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import java.util.Timer;
import java.util.TimerTask;
import testndk.testservice.interf.ICountService;
/**
 * <h3>Description</h3>
 * TODO
 * <h3>Author</h3> luzhenbang
 * <h3>Date</h3> 2016/6/1 9:44
 * <h3>Copyright</h3> Copyright (c)2016 Shenzhen Tentinet Technology Co., Ltd. Inc. All rights reserved.
 */
public class CustomInfaceService extends Service {

    /** 计时器*/
    private Timer timer;
    private  int temp = 0;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 21:
                    if (temp == 100){
                        temp = 0;
                    }else {
                        temp ++ ;
                    }
                    break;
            }
        }
    };

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new ServiceBinder();
    }
    @Override
    public void onCreate() {
        timer = new Timer();
        timer.schedule(new MyTimerTask(), 0, 1000);
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }
    /**计时器*/
    class MyTimerTask extends TimerTask {
        @Override
        public void run() {
            Message message = handler.obtainMessage();
            message.what = 21;
            handler.sendMessage(message);
        }
    }
    /**
     * 自定义 Binder
     */
     public  class ServiceBinder extends Binder implements ICountService {

        @Override
        public int getCurrentLoad() {
            return temp;
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (timer != null){
            timer.cancel();
        }
    }
}
